package com.changyue.bleHelper;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSONObject;
import com.changyue.util.EmptyUtil;

import java.text.DecimalFormat;

public class BLEDeviceConfig {

    public static final String period_unit = "秒";
    public static final String temp_unit = "℃";
    public static final  DecimalFormat df = new DecimalFormat("0.00");

    public String typeName = "温度控制器";
    public Integer period = 1;
    public Double targetTemp = 20.0;

    private static BLEDeviceConfig instance = null;

    public BLEDeviceConfig() {

    }

    public String getFormatData(float temp) {
        return df.format(temp);
    }

    public String getTypeName() {
        return EmptyUtil.isEmpty(typeName) ? "去设置" : typeName;
    }

    public String getPeriod() {
        return period + "";
    }

    public String getPeriodUnit() { return getPeriod() + period_unit; }

    public String getTargetTemp() {
        return df.format(targetTemp);
    }

    public String getTargetTempUnit() {
        return getTargetTemp() + temp_unit;
    }

    public static BLEDeviceConfig getInstance() {
        if (instance == null) {
            instance = new BLEDeviceConfig();
        }
        return instance;
    }

    public static void readConfig(Context context) {
        SharedPreferences sp = context.getSharedPreferences(BLEConstant.SP_PARAM, Context.MODE_PRIVATE);
        String jsonStr = sp.getString(BLEConstant.SP_PARAM_DATA, null);
        if (EmptyUtil.isEmpty(jsonStr)){
            getInstance();
            return;
        }

        BLEDeviceConfig obj = JSONObject.parseObject(jsonStr, BLEDeviceConfig.class);
        if (EmptyUtil.isNotEmpty(obj)) {
            instance = obj;
        } else {
            getInstance();
        }
    }

    public static void writeConfig(Context context) {
        SharedPreferences sp = context.getSharedPreferences(BLEConstant.SP_PARAM, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String jsonStr = JSONObject.toJSONString(getInstance());
        editor.putString(BLEConstant.SP_PARAM_DATA, jsonStr);
        editor.apply();
    }
}
